/**
 *@描述：创建知识-知识关联页面，设置本知识的关联知识。
 *@作者：殷健
 *@创建时间：2022/7/7
 *@最后修改时间：2022/7/7
 */

import { useRef, useEffect, useState, Key } from 'react';
import {Link} from 'umi';
import {
    Button,
    Typography,
    List,
    Card,
    Popconfirm,
    Tag,
    Modal,
    Space,
    Spin,
    Pagination,
    PaginationProps,
    message,
    Checkbox,
    Input,
    Empty,
} from 'antd';
import ProForm,{ ProFormInstance, ProFormRadio,ProFormItem } from '@ant-design/pro-form';
import ProTable from '@ant-design/pro-table';
import type { CheckboxChangeEvent } from 'antd/es/checkbox';
import { getAuthorStr } from '@/utils/func';
import {PlusOutlined, LinkOutlined, DeploymentUnitOutlined, SaveOutlined,SearchOutlined } from '@ant-design/icons';

import {
    KnowledgeAssociativeRequest,
    KnowledgeSearchRequest,
    AssociativeRequest, getAssociativeTypeData, AssociativeDelRequest
} from '../../service';

import styles from './style.less';
import {useUpdateEffect} from "ahooks";
import {useModel} from "@@/plugin-model/useModel";

const { Text } = Typography;
const Relevance = (
    {
        title,
        knowledgeId,
        curSection,
        setCurSection,
    }:{
        title:string;
        knowledgeId?:string;
        curSection:AircasKB.Knowledge.SectionItem;
        setCurSection?: (val: AircasKB.Knowledge.SectionItem) => void;
    }
) => {

    //todo: 设置页面状态
    const [activeTab, setActiveTab] = useState<string>('0');
    const [pageSize] = useState<string>('5');
    const [currentPage,setCurrentPage] = useState<string>('1');
    const [total,setTotal] = useState<string>('0');
    const [ loading,setLoading ] = useState(false);
    const [showAddRelevanceModal, setShowAddRelevanceModal] = useState<boolean>(false);
    const [data,setData] = useState<AircasKB.Knowledge.AssociativeBodyView[]>([]);

    //页面初始化函数
    //todo: useEffect函数
    useEffect(() => {
        if(!knowledgeId){
            message.warn("请首先进入基本信息页面，填写基本信息！");
            setCurSection?.({
                id: 'basic',
                title: '基本信息'
            })
        }else{
            NgetowledgeAssociative();
        }

    }, [activeTab,currentPage]);

    //todo: useUpdateEffect函数
    useUpdateEffect(() => {
        setCurSection?.(curSection);
    }, [curSection]);

    //查询关联的知识，包括我关联的和关联我的,调用KnowledgeAssociativeRequest接口
    //todo: 查询关联的知识，包括我关联的和关联我的
    const NgetowledgeAssociative = async () => {
        setLoading(true);
        const res:AircasKB.ResponseType<AircasKB.Knowledge.KnowledgeAssociativeResponse> = await KnowledgeAssociativeRequest({
            bodyType:activeTab,
            knowledgeId:knowledgeId,
            pageSize:pageSize,
            currentPage:currentPage,
        });
        if(res.data && res.code == 200){
            // @ts-ignore
            setData(res.data.list);
            // @ts-ignore
            setTotal(res.data.total);
        }
        setLoading(false);
    }

    //分页-点击野马触发函数
    //todo: 分页-点击野马触发函数
    const onChange: PaginationProps['onChange'] = page => {
        setCurrentPage(page.toString());
    };

    //解除关联函数，调用AssociativeDelRequest接口
    //todo: 解除关联
    const doRemoveRelevance = async (obj: any) => {
        //TODO 删除
        const res:AircasKB.ResponseType<AircasKB.Knowledge.AssociativeDelResponse> = await AssociativeDelRequest({
            knowledgeId:knowledgeId,
            refKnowledgeId:obj.id
        })
        if(res.code == 200){
            NgetowledgeAssociative();
        }
    };

    return (
        <div className={styles.wrapper}>
            <div className={styles.subTitle} style={{ marginBottom: 0 }}>
                <Text>知识关联</Text>
            </div>
            <div className={styles.formControl}>
                <Card
                    size="small"
                    bordered={false}
                    tabList={[
                        { key: '0', tab: '我关联的' },
                        { key: '1', tab: '关联我的' },
                    ]}
                    activeTabKey={activeTab}
                    onTabChange={(key) => {
                        setActiveTab(key);
                    }}
                    bodyStyle={{ padding: 15 }}
                >
                    <List
                        loading={loading}
                        itemLayout="horizontal"
                        dataSource={data}
                        renderItem={(item:any) => (
                            <List.Item
                                actions={[
                                    activeTab === '0' && (
                                        <Popconfirm
                                            title="确认解除关联吗？"
                                            okText="确定"
                                            cancelText="取消"
                                            onConfirm={() => doRemoveRelevance(item)}
                                        >
                                            <Button size="small" type="link" danger>
                                                解除关联
                                            </Button>
                                        </Popconfirm>
                                    ),
                                ]}
                            >
                                <List.Item.Meta
                                    avatar={<LinkOutlined />}
                                    title={item.title}
                                    description={getAuthorStr({value:item.authorNames})}
                                />
                                <Tag>{item.refTypeName}</Tag>
                            </List.Item>
                        )}
                    />
                    <Pagination showQuickJumper current={Number(currentPage)||1} pageSize={Number(pageSize) || 5} total={Number(total)||0} onChange={onChange}/>
                    <br/>
                    {activeTab === '0' && (
                        <Button
                            type="dashed"
                            size="large"
                            block
                            icon={<PlusOutlined />}
                            onClick={() => setShowAddRelevanceModal(true)}
                        >
                            添加关联
                        </Button>
                    )}

                </Card>
            </div>
            {showAddRelevanceModal && (
                <AddRelevanceModal
                    knowledgeId = {knowledgeId}
                    onSucess={NgetowledgeAssociative}
                    setShowAddRelevanceModal={setShowAddRelevanceModal}
                    show={showAddRelevanceModal}
                    onCancel={() => setShowAddRelevanceModal(false)}
                ></AddRelevanceModal>
            )}
        </div>
    );
};


//添加知识关联组件
//todo: 添加知识关联组件
const AddRelevance = (
    {
        knowledgeId,
        onSucess,
        setShowAddRelevanceModal,
    }:{
        knowledgeId?:string;
        onSucess?:()=>void;
        setShowAddRelevanceModal?:(val:boolean)=>void;
    }
) => {

    //todo: 设置组件状态
    const formRef = useRef<ProFormInstance>();
    const [selectedRowKeys, setSelectedRowKeys] = useState<Key[]>([]);
    const [ list,setList ] = useState<any[]>([]);
    const [ currentPage,setCurrentPage ] = useState("1");
    const [ total,setTotal ] = useState("0");
    const [ pageSize ] = useState("5");
    const [ loading,setLoading ] = useState(false);
    const [sreachValue,setSreachValue] = useState("");
    const [authorId,setAuthorId] = useState("");
    const { initialState } = useModel('@@initialState');

    //组件初始化函数
    //todo: useEffect函数
    useEffect(()=>{
        gatKnowledgeSearch({});
    },[currentPage])

    //添加函数
    //todo: 保存
    const doSave = async (values: FormData) => {
        setLoading(true);
        //设置保存所需请求参数
        const requestParams:AircasKB.Knowledge.AssociativeRequestParams={
            knowledgeId:knowledgeId,
            refKnowledgeId:selectedRowKeys[0].toString(),
            ...values,
        }
        // console.log(requestParams);
        //调用AssociativeRequest接口，添加知识关联
        const res:AircasKB.ResponseType<AircasKB.Knowledge.AssociativeResponse> = await AssociativeRequest(requestParams)
        if(res.code){
            // @ts-ignore
            onSucess();
            // @ts-ignore
            setShowAddRelevanceModal(false);
            message.success("关联成功！");
        }
        else{
            message.error("关联失败！");
        }
        setLoading(false);
    };

    //查询知识列表，可通过关键字和是否限本人作品查询
    //todo: 知识列表查询
    const gatKnowledgeSearch = async (
        {
            keyword
        }:{
            keyword?:string;
    }) => {
        setLoading(true);
        const requestParams: AircasKB.Knowledge.KnowledgeSearchRequestParams={
            knowledgeId:knowledgeId,
            authorId:authorId,
            currentPage:currentPage,
            pageSize:pageSize,
            keyword:keyword,
        }
        // console.log(requestParams);
        const res:AircasKB.ResponseType<AircasKB.Knowledge.KnowledgeSearchResponse> = await KnowledgeSearchRequest(requestParams)
        if(res.code== 200){
            const result:any=[];
            // @ts-ignore
            if(res.data.list.length>0){
                res.data.list?.map((item)=>{
                    let auther:string="";
                    const authorNames = item.authorNames;
                    // @ts-ignore
                    for(let i=0;i<authorNames?.length;i++){
                        auther+=authorNames?.[i].toString()+',';
                    }
                    auther+='等'+item.authorNames?.length+'人';
                    result.push({
                        id:item.id,
                        title:item.title,
                        author:auther,
                    })
                })
            }
            setList(result);
            // @ts-ignore
            setTotal(res.data.total);
        }
        setLoading(false);
    }



    //分页-点击页码设置页码状态
    //todo: 分页，点击页码触发分页
    const onChange: PaginationProps['onChange'] = page => {
        setCurrentPage(page.toString());
    };

    //点击限本人的复选框触发，设置查询条件
    //todo: 点击限本人的复选框触发，设置查询条件
    const onCheckChange = (e: CheckboxChangeEvent) => {
        if(e.target.checked){
            // @ts-ignore
            setAuthorId(initialState.currentUser?.id);
        }
        else{
            setAuthorId("");
        }
        console.log(`checked = ${e.target.checked}`);
    };

    return (
        <div className={styles.stepsFormWrapper}>
            <ProForm
                formRef={formRef}
                layout="horizontal"
                className={styles.form}
                onFinish={doSave}
                labelCol={{
                    style: {
                        width: 80,
                    },
                }}
                submitter={false}
            >
                <ProFormItem>
                    <ProTable
                        loading={loading}
                        bordered
                        search={false}
                        options={{ search: false,setting:false }}
                        headerTitle={
                            <div>
                                <Input
                                    placeholder="请输入关键字"
                                    style={{ width: 270 }}
                                    onChange={(e)=>setSreachValue(e.target.value)}
                                ></Input>&nbsp;&nbsp;&nbsp;&nbsp;
                                <Checkbox onChange={onCheckChange}>限本人作品</Checkbox>
                                <Button
                                    size="large"
                                    type="primary"
                                    icon={<SearchOutlined />}
                                    style={{ marginLeft: 10 }}
                                    onClick={async ()=>{
                                        await gatKnowledgeSearch({
                                            keyword:sreachValue,
                                        })
                                    }}
                                >
                                    搜索
                                </Button>
                                {/*<Checkbox onChange={onCheckChange}>Checkbox</Checkbox>*/}
                            </div>

                        }
                        rowKey={'id'}
                        columns={[
                            {
                                dataIndex: 'title',
                                title: '知识标题',
                                ellipsis: true,
                            },
                            {
                                dataIndex: 'author',
                                title: '作者',
                                ellipsis: true,
                            },
                        ]}
                        pagination={false}
                        dataSource={list}
                        rowSelection={{
                            type: 'radio',
                            fixed: true,
                            onChange: setSelectedRowKeys,
                        }}
                    ></ProTable>
                    <Pagination showQuickJumper current={Number(currentPage)||1} pageSize={Number(pageSize) || 5} total={Number(total)||0}  onChange={onChange}/>
                </ProFormItem>

                <ProFormRadio.Group
                    name="refType"
                    label="类型"
                    radioType="button"
                    fieldProps={{
                        buttonStyle: 'solid',
                    }}
                    required
                    rules={[
                        {
                            required: true,
                            message: '请选择知识类型',
                        },
                    ]}
                    request={async ()=>{
                        const res:AircasKB.ResponseType<AircasKB.Knowledge.AssociativeTypeResponse[]> = await getAssociativeTypeData();
                        if(res.code == 200){
                            const result:any = [];
                            res.data.map((item)=>{
                                result.push({
                                    label:item.label,
                                    value:item.id
                                })
                            })
                            return result
                        }
                        else{
                            return []
                        }
                    }}
                />
                <ProFormItem>
                    <Button
                        size="large"
                        type="primary"
                        htmlType="submit"
                        icon={<SaveOutlined />}
                        style={{ marginLeft: 80 }}
                        loading={loading}
                    >
                        保存
                    </Button>
                </ProFormItem>

            </ProForm>
        </div>
    );
};

//todo: modal类型-弹出窗口，添加关联知识窗口
const AddRelevanceModal = (
    {
        show,
        onCancel,
        knowledgeId,
        onSucess,
        setShowAddRelevanceModal,
    }: {
        show: boolean;
        onCancel?: () => void;
        knowledgeId?:string;
        onSucess?:()=>void;
        setShowAddRelevanceModal?:(val:boolean)=>void }) => {
    return (
        <Modal
            title={
                <Space>
                    <DeploymentUnitOutlined />
                    新增关联
                </Space>
            }
            visible={show}
            width={'80%'}
            centered
            destroyOnClose={true}
            footer={false}
            bodyStyle={{ padding: 10}}
            onCancel={onCancel}
        >
            <AddRelevance knowledgeId={knowledgeId} onSucess={onSucess} setShowAddRelevanceModal={setShowAddRelevanceModal}/>
        </Modal>
    );
};


//todo: 关联知识列表组件
const RelevanceCardList = (
    {
        knowledgeId,
        data,
    }:{
        knowledgeId?:string;
        data?:AircasKB.Knowledge.SimpleKnowledgeView[];
    }
) => {
    const [ loading,setLoading ] = useState(false);
    // @ts-ignore
    const [ relData,setRelData ] = useState<AircasKB.Knowledge.SimpleKnowledgeView[]>(data);

    useEffect(()=>{
        setRelData(data);
    },[data])
    // const { data, loading } = useRequest(fakeRelevance);
    return (
        <Spin spinning={loading}>
            {relData && relData.length == 0 && <Empty image={Empty.PRESENTED_IMAGE_SIMPLE} />}
            {relData && relData.map((item) => {
                return (
                    <Card
                        key={item.id}
                        bordered
                        size="small"
                        title={
                            <Space>
                                <Tag color="#219adc">{item.type}</Tag>
                                {item.title}
                            </Space>
                        }
                        extra={
                            <Button size="small" type="link">
                                <Link target="_blank" to={`/knowledge/details/${item.id}`}>详情</Link>
                            </Button>
                        }
                        style={{ marginBottom: 20 }}
                        bodyStyle={{ padding: 10, maxHeight: 200, overflow: 'auto' }}
                    >
                        <div dangerouslySetInnerHTML={{__html:item && item.baseInfo}}>
                        </div>
                        {/*<Paragraph style={{ marginBottom: 0 }}></Paragraph>*/}
                    </Card>
                );
            })}
        </Spin>
    );
};

export default Relevance;
export { RelevanceCardList };
